package com.ruoyi.iot.controller;

import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.cmdb.spi.CmdbService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.iot.domain.IotCmd;
import com.ruoyi.iot.domain.IotProduct;
import com.ruoyi.iot.domain.dto.IotProductFilterDTO;
import com.ruoyi.iot.domain.vo.IotProductFilterListVO;
import com.ruoyi.iot.domain.vo.TreeVO;
import com.ruoyi.iot.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.iot.domain.IotProductFilter;
import com.ruoyi.iot.service.IIotProductFilterService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 数据筛选Controller
 *
 * @author ruoyi
 * @date 2023-03-02
 */
@RestController
@Slf4j
@RequestMapping("/product_filter")
public class IotProductFilterController extends BaseController
{
    @Autowired
    private IIotProductFilterService iotProductFilterService;

    /**
     * 树模型结构
     */
    @Autowired
    private TreeVoServiceImpl treeVoService;

    /**
     * 指令服务
     */
    @Autowired
    private IotCmdServiceImpl cmdbService;

    /**
     * 字段服务
     */
    @Autowired
    private IotProductFieldServiceImpl fieldService;

    /**
     * 产品服务
     */
    @Autowired
    private IotProductServiceImpl productService;


    /**
     * 查询数据筛选列表
     */
    @RequiresPermissions("iot:product_filter:list")
    @GetMapping("/list")
    public TableDataInfo list(IotProductFilter iotProductFilter)
    {
        startPage();
        List<IotProductFilter> list = iotProductFilterService.selectIotProductFilterList(iotProductFilter);


        List<IotProductFilterListVO> listVOS = new ArrayList<>();
        for(IotProductFilter item : list) {
            IotProductFilterListVO voItem = new IotProductFilterListVO();
            BeanUtils.copyProperties(item,voItem);

            if(!StringUtils.isEmpty(item.getFileds())) {
                StringBuilder fieldBuilder = new StringBuilder();
                String[] fieldIds = item.getFileds().split(",");
                for (String fieldId : fieldIds) {
                    if(fieldService.selectIotProductFieldById(Long.parseLong(fieldId)) != null){
                        String fieldName = fieldService.selectIotProductFieldById(Long.parseLong(fieldId)).getName();
                        fieldBuilder.append(fieldName).append(",");
                    }
                }
                String fields = fieldBuilder.deleteCharAt(fieldBuilder.length() - 1).toString();
                voItem.setFiledNames(fields);
            }
            if(item.getCmdId() != null){
                String cmdName = cmdbService.selectIotCmdById(item.getCmdId()).getName();
                voItem.setCmdName(cmdName);
            }

            log.info("item:" + JSON.toJSONString(item));
            if(item.getProductId() != null) {
                IotProduct iotProduct = productService.selectIotProductById(item.getProductId());

                log.info("iot:" + JSON.toJSONString(iotProduct));

                if(iotProduct != null) {
                    String productName = iotProduct.getName();
                    voItem.setProductName(productName);
                }
            }

            if(item.getEnable() != null) {

                if (item.getEnable() == 0) {
                    voItem.setEnable("关闭");
                }
                if (item.getEnable() == 1) {
                    voItem.setEnable("启用");
                }
            }

            listVOS.add(voItem);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 导出数据筛选列表
     */
    @RequiresPermissions("iot:product_filter:export")
    @Log(title = "数据筛选", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotProductFilter iotProductFilter)
    {
        List<IotProductFilter> list = iotProductFilterService.selectIotProductFilterList(iotProductFilter);
        ExcelUtil<IotProductFilter> util = new ExcelUtil<IotProductFilter>(IotProductFilter.class);
        util.exportExcel(response, list, "数据筛选数据");
    }

    /**
     * 获取数据筛选详细信息
     */
    @RequiresPermissions("iot:product_filter:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(iotProductFilterService.selectIotProductFilterById(id));
    }



    @GetMapping(value = "/tree")
    public AjaxResult tree()
    {

        return AjaxResult.success(treeVoService.filedFilterTreeVO());
    }






    /**
     * 新增数据筛选
     */
    @RequiresPermissions("iot:product_filter:add")
    @Log(title = "数据筛选", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotProductFilterDTO productFilterDTO)
    {
        IotProductFilter iotProductFilter = new IotProductFilter();
        BeanUtils.copyProperties(productFilterDTO,iotProductFilter);
        List<TreeVO.Node> voLists = productFilterDTO.getCheckNodes();
        if(voLists == null || voLists.size() ==0) {
            iotProductFilter.setProductId(null);
            iotProductFilter.setCmdId(null);
            iotProductFilter.setFileds(null);
        } else {
            TreeVO.Node head_node = voLists.get(0);
            if (head_node.getLevel() == 1) {
                return error("不可以选择产品");
            }
            if (head_node.getLevel() == 2) {
                voLists = head_node.getChildren();
                head_node = voLists.get(0);
            }

            if (head_node.getLevel() == 3) {
                Long cmdId = Long.parseLong(head_node.getParentId());

                IotCmd iotCmd = cmdbService.selectIotCmdById(cmdId);
                Long productId = iotCmd.getProductId();

                StringBuilder fieldBuilder = new StringBuilder();
                for (TreeVO.Node node : voLists) {
                    Long fieldId = Long.parseLong(node.getId());
                    fieldBuilder.append(fieldId).append(",");
                }
                String fileds = fieldBuilder.deleteCharAt(fieldBuilder.length() - 1).toString();

                iotProductFilter.setCmdId(cmdId);
                iotProductFilter.setProductId(productId);
                iotProductFilter.setFileds(fileds);
            }
        }

        return toAjax(iotProductFilterService.insertIotProductFilter(iotProductFilter));
    }

    /**
     * 修改数据筛选
     */
    @RequiresPermissions("iot:product_filter:edit")
    @Log(title = "数据筛选", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotProductFilterDTO productFilterDTO)
    {
        log.info("filter dto:" + JSON.toJSONString(productFilterDTO));

        IotProductFilter iotProductFilter = new IotProductFilter();
        BeanUtils.copyProperties(productFilterDTO,iotProductFilter);
        List<TreeVO.Node> voLists = productFilterDTO.getCheckNodes();
        if(voLists == null || voLists.size() ==0) {
            iotProductFilter.setProductId(null);
            iotProductFilter.setCmdId(null);
            iotProductFilter.setFileds(null);
        } else {
            TreeVO.Node head_node = voLists.get(0);
            if (head_node.getLevel() == 1) {
                return error("不可以选择产品");
            }
            if (head_node.getLevel() == 2) {
                voLists = head_node.getChildren();
                head_node = voLists.get(0);
            }

            if (head_node.getLevel() == 3) {
                Long cmdId = Long.parseLong(head_node.getParentId());

                IotCmd iotCmd = cmdbService.selectIotCmdById(cmdId);
                Long productId = iotCmd.getProductId();

                StringBuilder fieldBuilder = new StringBuilder();
                for (TreeVO.Node node : voLists) {
                    Long fieldId = Long.parseLong(node.getId());
                    fieldBuilder.append(fieldId).append(",");
                }
                String fileds = fieldBuilder.deleteCharAt(fieldBuilder.length() - 1).toString();

                iotProductFilter.setCmdId(cmdId);
                iotProductFilter.setProductId(productId);
                iotProductFilter.setFileds(fileds);
            }
        }
        return toAjax(iotProductFilterService.updateIotProductFilter(iotProductFilter));
    }

    /**
     * 删除数据筛选
     */
    @RequiresPermissions("iot:product_filter:remove")
    @Log(title = "数据筛选", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(iotProductFilterService.deleteIotProductFilterByIds(ids));
    }
}
